﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Device.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Device.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CardReaderRepository : Repository<CardReader, DefaultDbContext>
    {
        private readonly ILogger logger;

        public CardReaderRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<CardReaderRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        public IPagedList<CardReader> GetSysDevices(DeviceQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("card_reader");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(device_code Like @0 or corp_code like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            //sql.Where("is_deleted <> 1");
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public bool Exists(CardReader entity, int? id)
        {
            if (id.HasValue)
                return DbContext.Exists<CardReader>("device_code=@0 and id!=@1", entity.DeviceCode, id);
            return DbContext.Exists<CardReader>("device_code=@0", entity.DeviceCode);
        }

        public CardReader? GetSysDeviceByDeviceCode(string deviceCode)
        {
            Sql sql = Sql.Builder.Select("id").From("card_reader").Where("device_code=@0", deviceCode);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        /// <summary>
        /// 获取当前信息安全用户下的所有设备
        /// </summary>
        /// <param name="securityId"></param>
        /// <returns></returns>
        public IEnumerable<CardReader> GetCardReaderDeviceByCorpCode(string corpCode)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("CorpCode", corpCode);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"CardReaderDeviceByCorpCode:{corpCode}";
            }, () =>
            {
                Sql sql = Sql.Builder.Select("id").From("card_reader").Where("corp_code=@0", corpCode);
                return sql;
            });
        }
    }
}